<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="search">
				<el-form-item>
					<el-input v-model="search.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="queryRoles">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
<!--        <el-form-item>-->
<!--          <el-upload-->
<!--              class="upload-demo"-->
<!--              action="https://jsonplaceholder.typicode.com/posts/"-->
<!--              :on-preview="handlePreview"-->
<!--              :on-remove="handleRemove"-->
<!--              :before-remove="beforeRemove"-->
<!--              multiple-->
<!--              :limit="3"-->
<!--              :on-exceed="handleExceed"-->
<!--              :file-list="fileList">-->
<!--            <el-button size="small" type="primary">点击上传</el-button>-->
<!--          </el-upload>-->
<!--        </el-form-item>-->
			</el-form>
		</el-col>


		<!--列表-->
    <el-table :data="pageInfo.list" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="角色名字" width="120">
      </el-table-column>
      <el-table-column prop="sn" label="角色SN" width="180">
      </el-table-column>


      <el-table-column label="操作" width="240">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="primary" @click="handleRole(scope.$index, scope.row)">授权</el-button>
        </template>
      </el-table-column>
    </el-table>
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <!--
            el-pagination:表示分页
            size-change:每页条数改变的时候出发的方法
            @current-change: 当页数改变的时候
           :current-page: 绑定当前页数据
           :page-sizes="[100, 200, 300, 400]" : 每页多少条的选择
           :page-size="100" 每页的条数
           :total="400" 总条数
           layout="total, sizes, prev, pager, next, jumper"
      -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="search.currentPage"
          :page-sizes="[3, 5, 8, 10]"
          :page-size="100"
          style="float:right;"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageInfo.total">
      </el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog title="编辑" :visible.sync="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="部门简介" prop="intro">
          <el-input v-model="saveForm.intro" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门经理" prop="manager.username">
          <el-select v-model="saveForm.manager" placeholder="请选择" clearable value-key="id">
            <el-option
                v-for="item in managers"
                :key="item.id"
                :label="item.username"
                :value="item">
            </el-option>
          </el-select>

          <!--          <el-input v-model="saveForm.manager.username" auto-complete="off"></el-input>-->
        </el-form-item>

        <el-form-item label="上级部门">
          <el-cascader v-model="saveForm.parent"
                       :options="roletTree"
                       :props="{
							   checkStrictly: true,
							   label:'name',
							   value:'id'
							}"
                       clearable></el-cascader>
        </el-form-item>
<!--        <el-form-item label="路径" prop="path">-->
<!--          <el-input v-model="saveForm.path" auto-complete="off"></el-input>-->
<!--        </el-form-item>-->
        <el-form-item label="状态" prop="state">
          <el-input v-model="saveForm.state" auto-complete="off"></el-input>
        </el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="saveSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>
    <!--授权界面-->
    <el-dialog title="授权" :visible.sync="roleFormVisible" :close-on-click-modal="false">
      <el-form :model="roleForm" label-width="80px" :rules="saveFormRules" ref="roleForm">
        <el-form-item label="角色名称"  disabled prop="name" >
          <el-input v-model="roleForm.role.name"  disabled auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="name" disabled >
          <el-tree
              :props="props"
              :data="data"
              default-expand-all
              node-key="id"
              ref="tree"
              show-checkbox>
          </el-tree>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="roleFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addAuth" :loading="editLoading" >提交</el-button>
      </div>
    </el-dialog>


	</section>
</template>

<script>


	export default {
		data() {
			return {
        data:[],
        props: {
          label: 'name',
          children: 'children'
        },
        roleFormVisible: false,
        roleForm:{
          role:{id:null},
          permissionList:[]
        },
        managers:[],
        roletTree:[],
        search: {
					keyword: '',
          currentPage:1,
          pageSize:10
				},
        pageInfo:{
          list: [],
          total: 0
        },
				page: 1,
				listLoading: false,
				sels: [],//列表选中列

				saveFormVisible: false,//编辑界面是否显示
				editLoading: false,
				saveFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				//编辑界面数据
				saveForm: {
					id: null,
					name: '',
          intro:'',
          manager:{
					  id:null,
            username:''
          },
          parent:{
            id: null,
            name: ''
          },
          path:'',
          state:''
				},
			}
		},
		methods: {

      quetyAuthRLoeById(){
        this.$http.post("/role/roleAuth/"+this.roleForm.role.id)
            .then(res=>{
              res = res.data;
              if (res.success){
                var ids = res.data
                console.log(ids);
                this.$refs.tree.setCheckedKeys(ids)
              }
            })
            .catch(res=>{})
      }
      ,
		  //提交授权按钮
      addAuth(){
        this.roleForm.permissionList = this.$refs.tree.getCheckedNodes();
        // console.log(this.roleForm);//role行的对象，不包括树形表单
        this.$http.post("/role/roleAuth",this.roleForm)
            .then(res=>{
              var data = res.data;
              if (data.success){
                this.$message({type:"success",message:"授权成功"})
                this.roleFormVisible = false;
              }
            })
            .catch(res=>{})
      },
      // 查询权限树
      getTree(){
        this.$http.get("/permission/tree")
          .then(res=>{
            var data = res.data;
            // console.log(data);
            if (data.success){
              this.data=data.data
              // this.$refs.tree.setCheckedKeys([1448,1447]);
              this.quetyAuthRLoeById();
            }
          })
          .catch(res=>{})
      },
      handleRole(index,row){
        this.roleFormVisible = true
        this.roleForm.role = row
        this.getTree()
      },
		  //查询部门树
      getDeprTree(){
        this.$http.get("/role/roleTree")
            .then(res=>{
              console.log(res);
              res = res.data;
              console.log(res);
              if (res.success){
                this.roletTree=res.data
              }
            })
            .catch(res=>{})
      },
		  //获取管理员数组
      getManagers(){
          this.$http.get("/employee")
            .then(res=>{
              res = res.data;
              if (res.success){
                this.managers=res.data
              }
            })
            .catch(res=>{})
      },
		  //点击查询部门
      queryRoles(){
        this.search.currentPage=1
        this.getRoles()
      },
		  //每页条数变动
      handleSizeChange(val){
        this.search.pageSize = val
        this.getRoles()
      },
		  //当前页
			handleCurrentChange(val) {
			  //val指的当前页
        this.search.currentPage=val
				// this.page = val;
				this.getRoles();
			},
			//获取角色列表
			getRoles() {
        this.listLoading=true;
				this.$http.post("/role",this.search)
            .then(res=>{
              this.listLoading=false;
              res = res.data;
              console.log(res)
              if(res.success){
                // this.list = res.data.list
                // this.total= res.data.total
                this.pageInfo=res.data
              }
            })
            .catch(res=>{})
			},

			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					//NProgress.start();
					// let para = { id: row.id };
          console.log(row.id);
          this.$http.delete("/role/"+row.id)
            .then(res=>{
              res = res.data;
              this.listLoading = false;
              if (res.success){
                this.$message({type:"success",message:"删除成功"})
              }else {
                this.$message.error("删除失败"+res.msg)
              }
              this.search.currentPage= 1;
              this.getRoles();
            })
            .catch()
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.saveFormVisible = true;
				this.saveForm = row;
				var split = row.path.split("/");
				var data = []
        for (let i = 1; i <split.length-1; i++) {
          data.push(Number.parseInt(split[i]))
        }
        console.log(data);
        this.saveForm.parent = data
        if (!row.parent){
				  this.saveForm.parent={
				    id:null,
				    username:''
          }
        }
        if (!row.manager){
          this.saveForm.manager={
            id:null,
            name:''
          }
        }
        this.getManagers()
        this.getDeprTree()
			},
			//显示新增界面
			handleAdd: function () {
				this.saveFormVisible = true;
				this.saveForm = {
          id: null,
              name: '',
            intro:'',
            manager:{
          id:null,
              username:''
        },
          parent:{
            id: null,
                name: ''
          },
          path:'',
              state:''
				}
        this.getManagers()
        this.getDeprTree()
      },
			//编辑和新增保存信息
			saveSubmit: function () {
				this.$refs.saveForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							//NProgress.start();
							let para = Object.assign({}, this.saveForm);
							var parent =para.parent;
              if (parent.length >= 0){
                if (parent.length==0){
                  para.parent={id:null,name:""}
                }else{
                  para.parent={id:parent[parent.length-1],name:""}
                }
              }

							this.$http.put("/role",para)
                .then(res=>{
                  this.saveFormVisible=false
                  this.$message({type:"success" ,message:"操作成功"})
                  this.getRoles()
                })
                .catch(res=>{})
						});
					}
				});

			},
			//新增
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
        var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {type: 'warning'})
            .then(() => {
					    this.listLoading = true;
              this.$http.patch("/role",ids)
                  .then(res=>{
                    this.listLoading = false;
                    res = res.data;
                    if (res.success){
                      this.saveFormVisible=false
                      this.$message({message: '删除成功', type: 'success'});
                    }else {
                      this.saveFormVisible=false
                      this.$message.error("删除失败"+res.msg)
                    }
                    this.search.currentPage=1
                    this.getRoles();
                  })
                  .catch(res=>{})
             })
				    .catch(() => {

            });
			}
		},
		mounted() {
			this.getRoles();
		}
	}

</script>

<style scoped>

</style>


